<?php
App::uses('AppModel', 'Model');
class CreateLink extends AppModel {

	public $name = 'CreateLink';
	public $useTable = 'menus_multi';


	/**
	 * Get category
	 *
	 * @param string $cat_type
	 * @throws NotFoundException
	 * @return mixed
	 */
	public function getListCategory() {
		try{
			$results = $this->query("SELECT id, cat_name, cat_rewrite,cat_order, cat_type, cat_parent_id, cat_parent_rewrite
					FROM categories_multi
					WHERE cat_active = 1
					ORDER BY cat_type ASC, cat_order ASC
					");
			return  $results;
		} catch (Exception $e) {
			throw new NotFoundException(__('Invalid category'));
		}

	}
	/**
	 * Get level Menu parent
	 * @param number $id
	 * @return number $cat_level
	 */
	public function getLevelMenuParent($id = null){
		$query = array(
				'conditions' => array(
					'id' => $id,
					'mnu_active' => 1
				),
				'fields' => 'mnu_level, mnu_has_child',
		);
		try{
			$cat_parent = $this->find('first', $query);
			return $cat_parent['Menus']['mnu_level'];

		} catch (Exception $e) {
			throw new NotFoundException(__('Invalid Menu'));
		}
	}

	/**
	 * get all news follow category id
	 * @param string $iCat
	 */
	public function getListNews($iCat = null){
		$results = array();
		$table_field = Configure :: read('table_field');
		$result_category = $this->query(
				"SELECT id,cat_type,cat_name,cat_rewrite
				FROM categories_multi WHERE id = ". $iCat
		);

		$cat_type = $result_category[0]['categories_multi']['cat_type'];

		$cat_child = $this->query(
				"SELECT id
					FROM categories_multi
					WHERE cat_parent_id = ". $iCat
		);
		$list_id = $iCat;
		if (!empty($cat_child)){
			foreach ($cat_child as $child){
				$list_id .= "," . implode(',', $child['categories_multi']);
			}
		}

		foreach ($table_field as $key => $value){
			if($cat_type == $key){
				$sql	= "SELECT
							b." . $value[1] . " AS dat_id,
							b." . $value[3] . " AS dat_title,
							b." . $value[8] . " AS dat_rewrite,
							b." . $value[4] . " AS dat_date,
							c.cat_rewrite,c.cat_parent_rewrite,c.cat_type
							FROM categories_multi AS c, " . $value[0] . " AS b
							WHERE c.id = b." . $value[2] . "
							AND c.cat_type = '" . $key . "'
							AND b.category_id IN (" . $list_id . ") AND b." . $value[6] . " = 1 AND b." . $value[7] . " = 0
							ORDER BY b." . $value[4] . " DESC";

				$results = $this->query($sql);
				break;
			}
		}

		return  $results;
	}

}